package com.anfeng.cms.filter;

import com.anfeng.cms.api.support.ResDto;
import com.anfeng.cms.util.JsonMapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 吴朋
 * @date 2019/7/16
 */
public class AuthFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        String path = ((HttpServletRequest) servletRequest).getServletPath();
        // 登陆页面无需过滤
        if (path.indexOf("/login") > -1 || path.indexOf("/static/") > -1 || path.indexOf(".ico") > -1) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (session.getAttribute("loginUser") == null) {
            // 表示从api接口过来的数据
            if (path.indexOf("/api/") > -1) {
                ResDto resDto = new ResDto();
                resDto.setStatus(401);
                resDto.setMsg("用户未登录");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json");
                response.getWriter().write(JsonMapper.defaultMapper().toJson(resDto));
            } else {
                response.sendRedirect("/login");
            }
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
